import React, { useCallback, useEffect, useState } from 'react'
import { List } from '../../axiosAPI/ljc';
import '../../scss/ljc.scss'
import { useNavigate } from 'react-router-dom';
import { TodoListO } from '@react-vant/icons'
import { SyncOutlined, DownOutlined, UserOutlined, DeleteTwoTone, PlusCircleTwoTone } from '@ant-design/icons';
import { Form, Input, Table, Select, Radio, Drawer, Tree, Dropdown, message, Upload, Modal } from 'antd';
import { Button } from 'react-vant';
export default function Student() {
    let [list, setList] = useState([])
    let [list1, setList1] = useState([])
    let [treeData, setTreeData] = useState([])
    let [name, setName] = useState('')
    let [xh, setXh] = useState('')
    let [sex, setSex] = useState('')
    let [clazzList, setClazzList] = useState([])
    const [messageApi, contextHolder] = message.useMessage();
    let [upName, setUpName] = useState()
    let [upXh, setUpXh] = useState('')
    let [upSex, setUpSex] = useState('')
    let [upAddress, setUpAddress] = useState('')
    let [upIce, setUpIce] = useState('')
    let [upPhone, setUpPhone] = useState('')
    let [upClass, setUpClass] = useState('')
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalOpen1, setIsModalOpen1] = useState(false);
    const [isModalOpen2, setIsModalOpen2] = useState(false);
    const [componentSize, setComponentSize] = useState('default');
    let [addName, setAddName] = useState('')
    let [addphone, setAddphone] = useState('')
    let [addIce, setAddIce] = useState('')
    let [addAddress, setAddAddress] = useState('')
    let [addtid, setAddtid] = useState('')
    let [addClazz, setAddClazz] = useState('')
    let [addSex, setAddsex] = useState('')
    let [addCard, setAddCard] = useState('')
    let [names, setNames] = useState('')
    let [ids, setIds] = useState('')
    let [xueyuan, setXueyuan] = useState('')
    let [aids, setAids] = useState('')
    const { Option } = Select;
    const [open, setOpen] = useState(false);
    let getlist = async () => {
        let { data: { data } } = await List({
            url: '/ljc/studentList',
        })
        setList(data)
    }
    let getClazzList = async () => {
        let { data: { data } } = await List({
            url: 'ljc/clazzList'
        })
        setClazzList(data)
    }
    let getlist1 = useCallback(async () => {
        let { data: { data } } = await List({
            url: '/ljc/studentList1',
            method: 'post',
            data: {
                name,
                xh,
                sex,
                aid: aids
            }
        })
        setList(data)
    }, [name,xh,sex,aids])
   
    
    let getlist2 = useCallback(async () => {
        let { data: { data } } = await List({
            url: '/ljc/stage',
        })  
        setTreeData(data)
    }, [treeData])
    const onChange = (e) => {
        console.log('radio checked', e.target.value);
        setSex(e.target.value);
    };
    const onChange1 = (e) => {
        console.log('radio checked', e.target.value);
        setUpSex(e.target.value);
    };
    const onChange2 = (e) => {
        console.log('radio checked', e.target.value);
        setAddsex(e.target.value);
    };
    useEffect(() => {
        getlist()
        getClazzList()
        getlist2()
    }, [])

    const showDrawer = (id) => {
        setOpen(true);
        let a = list.filter(item => item._id == id)
        setList1(a)
        setUpName(a[0].name)
        setUpXh(a[0].tid)
        setUpSex(a[0].sex == true ? 1 : 2)
        setUpAddress(a[0].address)
        setUpIce(a[0].ice)
        setUpPhone(a[0].phone)
        setUpClass(a[0].clazz._id)
    };
    const onClose = () => {
        setOpen(false);
    };
    const columns = [
        {
            title: '序号',
            render: (_, record, index) => index + 1
        },
        {
            title: '学生名称',
            dataIndex: 'name',
        },
        {
            title: '学号',
            dataIndex: 'tid',
            sorter: (a, b) => a.tid - b.tid,
        },
        {
            title: '性别',
            render: (_, record) => {
                return record.sex == true ? '男' : '女'
            }
        },
        {
            title: '家庭住址',
            dataIndex: 'address'
        },
        {
            title: '紧急联系人',
            dataIndex: 'ice'
        },
        {
            title: '紧急联系人电话',
            dataIndex: 'phone'
        },
        {
            title: '班级',
            render: (_, record) => {
                return record.clazz?.name
            }
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <a onClick={() => {
                        showDrawer(_._id)
                    }}>操作</a>
                </div>
            ),
        },
    ];
    const onSelect = async (aid, name) => {
        // console.log(aid, name, '1111111111111111111');
        let { data: { data } } = await List({
            url: '/ljc/studentList1',
            method: 'post',
            data: {
                name,
                xh,
                sex,
                aid: aid
            }
        })
        console.log(data);

        setList(data)
    };
    let sou = () => {
        getlist1()
    }
    let reset = () => {
        setName('')
        setXh('')
        setSex('')
    }
    let save = async () => {
        let { data: { code } } = await List({
            method: 'post',
            url: '/ljc/upDateStudent',
            data: {
                id: list1[0]._id,
                name: upName,
                ice: upIce,
                phone: upPhone,
                tid: upXh,
                address: upAddress,
                clazz: upClass,
                sex: upSex
            }
        })
        if (code === 200) {
            getlist()
            onClose()
        }
    }
    const handleButtonClick = (e) => {

        setIsModalOpen(true);


    };
    const handleMenuClick = async (e) => {
        if (e.key === '1') {
            console.log('导入');
        } else if (e.key === '2') {
            console.log('导出');

            let { data: { code } } = await List({
                url: '/ljc/exportStudent'
            })
            if (code === 200) {
                messageApi.open({
                    type: 'success',
                    content: '导出成功',
                });
            }
        }
    };
    const items = [
        {
            label: <Upload
                name="file"
                className="avatar-uploader"
                showUploadList={false}
                action="http://localhost:3001/ljc/upload1"
                onChange={() => {
                    getlist()
                    messageApi.open({
                        type: 'success',
                        content: 'This is a success message',
                    });
                }}
            >
                批量导入
            </Upload>,
            key: '1',
            icon: <UserOutlined />,
            render: <button></button>
        },
        {
            label: '批量导出',
            key: '2',
            icon: <UserOutlined />,
        },
    ];
    const menuProps = {
        items,
        onClick: handleMenuClick,
    };
    const handleOk = async () => {
        setIsModalOpen(false);
        let { data: { code } } = await List({
            method: 'post',
            url: '/ljc/addStudent',
            data: {
                name: addName,
                phone: addphone,
                ice: addIce,
                address: addAddress,
                tid: addtid,
                clazz: addClazz,
                sex: addSex === 1 ? true : false,
                card: addCard,
                img: '/王佳龙001.jpg'
            }
        })
        if (code === 200) {
            getlist()
            setAddName('')
            setAddphone('')
            setAddIce('')
            setAddAddress('')
            setAddtid('')
            setAddClazz('')
            setAddsex('')
        }
    };

    const handleOk1 = async () => {
        setIsModalOpen1(false);
        let { data: { code } } = await List({
            url: '/ljc/addTree',
            data: {
                id: ids,
                name: names,
                creator:sessionStorage.getItem('uid')||'66d02419a5ff158b2695e15f'
            },
            method: 'post'
        })
        if (code === 200) {
            getlist2()
            getClazzList()
            setNames('')
        }
    };
    const handleOk2 = async () => {
        setIsModalOpen2(false);
        let { data: { code } } = await List({
            url: '/ljc/addXueyuan',
            data: {
                name: xueyuan
            },
            method: 'post'
        })
        if (code === 200) {
            getlist2()
            getClazzList()
            setXueyuan('')
        }
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const handleCancel1 = () => {
        setIsModalOpen1(false);
    };
    const handleCancel2 = () => {
        setIsModalOpen2(false);
    };
    const onFormLayoutChange = ({ size }) => {
        setComponentSize(size);
    };
    //删除tree数据
    let del = async (id) => {
        let { data: { code } } = await List({
            url: '/ljc/delTree',
            data: {
                id: id
            },
            method: 'post'
        })
        if (code === 200) {
            getlist2()
        }
    }

    let add = async (id) => {
        setIds(id)
        setIsModalOpen1(true);
    }
    let addXu = async () => {
        setIsModalOpen2(true);

    }
    const CustomTitle = (item) => {
        let { title: { aid, name } } = item
        let arr = clazzList.map(item => item._id)
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '5px' }}>
                <span style={{ flex: 1, cursor: 'pointer' }} onClick={() => { onSelect(aid, name) }}>
                    {name}
                </span>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <DeleteTwoTone onClick={() => { del(aid) }} style={{ marginLeft: '5px' }} />
                    {!arr.includes(aid) && (
                        <PlusCircleTwoTone style={{ marginLeft: '5px' }} onClick={() => { add(aid) }} />
                    )}
                </div>
            </div>
        );
    };
    return (
        <div id='ljcStudent'>
            <div className='header'>
                <h3>学生管理</h3>
            </div>
            <div className='body'>
                <div className="left">
                    <Tree
                        showLine
                        switcherIcon={<DownOutlined />}
                        fieldNames={{ title: 'name', key: 'name', children: 'children' }}
                        treeData={treeData}
                        style={{ marginTop: '20px', width: '100%' }}
                        titleRender={(node) => <CustomTitle title={node} />}
                    >
                    </Tree>
                    <Button style={{ margin: '20px 50px', width: '50%' }} onClick={addXu}>添加学院</Button>
                </div>
                <div className="right">
                    <div className="rightHeader">
                        <div className="sou">
                            <div className='souLeft'>
                                <Input placeholder="请输入姓名" style={{ width: '250px' }} value={name} onChange={(e) => { setName(e.target.value) }} />
                                <Input placeholder="请输入学号" style={{ width: '250px' }} value={xh} onChange={(e) => { setXh(e.target.value) }} />
                                <div>
                                    <Radio.Group onChange={onChange} value={sex} style={{ display: 'flex' }}>
                                        <Radio value={1}>男</Radio>
                                        <Radio value={2}>女</Radio>
                                    </Radio.Group>
                                </div>
                                <Button style={{ width: '100px' }} icon={<TodoListO />} color='rgb(64,169,255)' onClick={sou}> 查询</Button>
                                <Button style={{ width: '100px' }} icon={<SyncOutlined />} onClick={reset}> 重置</Button>
                            </div>
                            <div className='souRight'>
                                <Dropdown.Button menu={menuProps} onClick={handleButtonClick}>
                                    添加学生
                                </Dropdown.Button>
                            </div>
                        </div>
                    </div>
                    <div className="rightBody">
                        <Table
                            columns={columns}
                            dataSource={list}
                            rowKey={record => record._id}
                        />
                        <div>
                            <Drawer
                                width={720}
                                onClose={onClose}
                                open={open}
                                style={{ overflow: 'hidden' }}
                            >   {
                                    list1.length > 0 && <div style={{ display: 'flex' }}>
                                        <img src='/liu.png'></img>
                                        <p style={{ marginTop: '10px' }}>
                                            姓名 : {list1[0].name}<br />
                                            班级 : {list1[0].clazz.name}
                                        </p>
                                        <div style={{ position: 'absolute', right: '200px', top: '90px' }}>
                                            <a style={{ marginRight: "15px" }} onClick={() => {
                                                List({ url: `/ljc/studel`, method: 'post', data: { id: list1[0]._id } })
                                                getlist()
                                                onClose()
                                            }}>删除</a>
                                            <a onClick={save}>保存</a>
                                        </div>
                                        <img style={{ position: 'absolute', right: '10px' }} onClick={onClose} src='/xiao.png'></img>
                                    </div>
                                }
                                <div style={{ display: 'flex', flexWrap: 'wrap', marginTop: '20px' }}>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>学生姓名:</label><br />
                                        <input type='text' style={{ marginTop: '5px', width: '200px' }} value={upName} onChange={(e) => { setUpName(e.target.value) }}></input>
                                    </div>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>学号:</label><br />
                                        <input type='text' style={{ marginTop: '5px', width: '200px' }} value={upXh} onChange={(e) => { setUpXh(e.target.value) }}></input>
                                    </div>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>性别:</label><br />
                                        {/* <input type='text' style={{ marginTop: '5px', width: '200px' }} value={upSex} onChange={(e) => { setUpSex(e.target.value) }}></input> */}
                                        <Radio.Group onChange={onChange1} value={upSex} style={{ display: 'flex' }}>
                                            <Radio value={1}>男</Radio>
                                            <Radio value={2}>女</Radio>
                                        </Radio.Group>
                                    </div>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>家庭住址:</label><br />
                                        <input type='text' style={{ marginTop: '5px', width: '300px' }} value={upAddress} onChange={(e) => { setUpAddress(e.target.value) }}></input>
                                    </div>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>紧急联系人:</label><br />
                                        <input type='text' style={{ marginTop: '5px', width: '200px' }} value={upIce} onChange={(e) => { setUpIce(e.target.value) }}></input>
                                    </div>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>紧急联系人电话:</label><br />
                                        <input type='text' style={{ marginTop: '5px', width: '200px' }} value={upPhone} onChange={(e) => { setUpPhone(e.target.value) }}></input>
                                    </div>
                                    <div style={{ width: '48%', marginBottom: '20px' }}>
                                        <label>班级:</label><br />
                                        <select style={{ marginTop: '5px', width: '200px' }} value={upClass} onChange={(e) => { setUpClass(e.target.value) }}>
                                            <option value=''>请选择</option>
                                            {
                                                clazzList.map(item => (
                                                    <option key={item._id} value={item._id} checked={upClass === item._id ? true : false}>{item.name}</option>
                                                ))
                                            }
                                        </select>
                                    </div>
                                </div>
                            </Drawer>
                        </div>

                    </div>
                </div>
            </div>
            <Modal title="添加学生" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <hr style={{ color: 'gray' }} />
                <Form
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 14,
                    }}
                    layout="horizontal"
                    initialValues={{
                        size: componentSize,
                    }}
                    onValuesChange={onFormLayoutChange}
                    size={componentSize}
                    style={{
                        maxWidth: 600,
                        marginTop: '15px'
                    }}
                >
                    <Form.Item label="姓名">
                        <Input type='text' placeholder='请选择' value={addName} onChange={(e) => { setAddName(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="学号">
                        <Input type='text' placeholder='请选择' value={addtid} onChange={(e) => { setAddtid(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="身份证">
                        <Input type='text' placeholder='请选择' value={addCard} onChange={(e) => { setAddCard(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="性别">
                        <Radio.Group onChange={onChange2} value={addSex} style={{ display: 'flex' }}>
                            <Radio value={1}>男</Radio>
                            <Radio value={2}>女</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="地址">
                        <Input type='text' placeholder='请选择' value={addAddress} onChange={(e) => { setAddAddress(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="联系人">
                        <Input type='text' placeholder='请选择' value={addIce} onChange={(e) => { setAddIce(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="联系人电话">
                        <Input type='text' placeholder='请选择' value={addphone} onChange={(e) => { setAddphone(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="班级">
                        <select style={{ marginTop: '5px', width: '275px', height: '30px', borderRadius: '7%', border: '1px solid gray' }} value={addClazz} onChange={(e) => { setAddClazz(e.target.value) }}>
                            <option value=''>请选择</option>
                            {
                                clazzList.map(item => (
                                    <option key={item._id} value={item._id} checked={upClass === item._id ? true : false}>{item.name}</option>
                                ))
                            }
                        </select>
                    </Form.Item>

                </Form>
            </Modal>

            <Modal title="添加" open={isModalOpen1} onOk={handleOk1} onCancel={handleCancel1}>
                <hr style={{ color: 'gray' }} />
                <Form
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 14,
                    }}
                    layout="horizontal"
                    initialValues={{
                        size: componentSize,
                    }}
                    onValuesChange={onFormLayoutChange}
                    size={componentSize}
                    style={{
                        maxWidth: 600,
                        marginTop: '15px'
                    }}
                >
                    <Form.Item label="名称">
                        <Input type='text' value={names} onChange={(e) => { setNames(e.target.value) }} />
                    </Form.Item>
                </Form>
            </Modal>
            <Modal title="添加学院  " open={isModalOpen2} onOk={handleOk2} onCancel={handleCancel2}>
                <hr style={{ color: 'gray' }} />
                <Form
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 14,
                    }}
                    layout="horizontal"
                    initialValues={{
                        size: componentSize,
                    }}
                    onValuesChange={onFormLayoutChange}
                    size={componentSize}
                    style={{
                        maxWidth: 600,
                        marginTop: '15px'
                    }}
                >
                    <Form.Item label="地址">
                        <Input type='text' placeholder='请选择' value={xueyuan} onChange={(e) => { setXueyuan(e.target.value) }} />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
